<template>
  <div class="admin-dashboard">
    <el-card>
      <h2>管理员仪表盘</h2>
      <p>欢迎来到生鲜供应链管理系统后台！</p>
      <el-row :gutter="20" class="dashboard-stats">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-title">用户总数</div>
            <div class="stat-value">{{ stats.total_users || 0 }}</div>
            <div class="stat-trend">
              <span :class="{ 'up': userGrowth > 0, 'down': userGrowth < 0 }">
                {{ userGrowth > 0 ? '+' : '' }}{{ userGrowth }}%
              </span>
              较上月
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-title">产品总数</div>
            <div class="stat-value">{{ stats.total_products || 0 }}</div>
            <div class="stat-trend">
              <el-tag size="small" type="warning" v-if="stats.low_stock_products > 0">
                {{ stats.low_stock_products }} 个库存不足
              </el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-title">订单总数</div>
            <div class="stat-value">{{ stats.total_orders || 0 }}</div>
            <div class="stat-trend">
              <el-tag size="small" type="danger" v-if="stats.pending_orders > 0">
                {{ stats.pending_orders }} 个待处理
              </el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-title">配送任务</div>
            <div class="stat-value">{{ stats.total_deliveries || 0 }}</div>
            <div class="stat-trend">
              <el-tag size="small" type="info" v-if="stats.pending_deliveries > 0">
                {{ stats.pending_deliveries }} 个进行中
              </el-tag>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="dashboard-charts">
        <!-- 用户注册趋势 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>订单趋势</span>
                <el-radio-group v-model="userChartRange" size="small">
                  <el-radio-button label="week">本周</el-radio-button>
                  <el-radio-button label="month">本月</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <v-chart class="chart" :option="orderTrendOption" autoresize />
          </el-card>
        </el-col>
        
        <!-- 订单分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>订单状态分布</span>
              </div>
            </template>
            <v-chart class="chart" :option="orderDistributionOption" autoresize />
          </el-card>
        </el-col>
      </el-row>

      <!-- 最近活动时间线 -->
      <el-card class="timeline-card">
        <template #header>
          <div class="chart-header">
            <span>系统动态</span>
          </div>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in recentActivities"
            :key="index"
            :type="activity.type"
            :timestamp="activity.time"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册必要的 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

const stats = ref({
  total_users: 0,
  total_products: 0,
  total_orders: 0,
  total_deliveries: 0,
  pending_orders: 0,
  low_stock_products: 0,
  pending_deliveries: 0
})

const userChartRange = ref('week')
const userGrowth = ref(15) // 示例数据
const recentActivities = ref([])

// 在 stats ref 后添加新的数据结构
const orderTrendData = ref({
  today: 0,
  week: [0, 0, 0, 0, 0, 0, 0],
  month: new Array(30).fill(0)
})

// 获取用户总数和注册趋势
const fetchUsers = async () => {
  try {
    console.log('Fetching users...')
    const response = await request.get('/api/users/get_users/')
    console.log('Users response:', response)
    stats.value.total_users = response.length
    
    // 处理用户注册时间，生成趋势数据
    const registrationDates = response.map(user => new Date(user.date_joined))
    updateUserTrendData(registrationDates)
    
    // 添加最新注册用户到动态
    const recentUsers = response
      .sort((a, b) => new Date(b.date_joined) - new Date(a.date_joined))
      .slice(0, 3)
    
    recentUsers.forEach(user => {
      recentActivities.value.push({
        type: 'success',
        content: `新用户 ${user.username} 加入系统`,
        time: new Date(user.date_joined).toLocaleString()
      })
    })
  } catch (error) {
    console.error('获取用户数据失败:', error)
  }
}

// 获取产品数据
const fetchProducts = async () => {
  try {
    console.log('Fetching products...')
    // 使用模拟数据，与其他前端页面保持一致
    const mockProducts = [
      {
        id: 1,
        name: '新鲜苹果',
        stock: 8,
        price: 5.99
      },
      {
        id: 2,
        name: '有机胡萝卜',
        stock: 15,
        price: 3.99
      },
      {
        id: 3,
        name: '生菜',
        stock: 5,
        price: 2.99
      }
    ]

    // 更新统计数据
    stats.value.total_products = mockProducts.length
    stats.value.low_stock_products = mockProducts.filter(product => product.stock < 10).length
    
    // 添加低库存产品到动态
    const lowStockProducts = mockProducts.filter(product => product.stock < 10)
    lowStockProducts.forEach(product => {
      recentActivities.value.push({
        type: 'warning',
        content: `产品 ${product.name} 库存不足（${product.stock}）`,
        time: new Date().toLocaleString()
      })
    })

    console.log('Mock products loaded:', stats.value)
  } catch (error) {
    console.error('获取产品数据失败:', error)
  }
}

// 获取订单数据
const fetchOrders = async () => {
  try {
    console.log('Fetching orders...')
    
    // 使用与配送员仪表盘相同的模拟数据
    const mockOrders = [
      {
        id: 1,
        order_number: 'ORD20240301001',
        customer_name: '公司A',
        address: '北京市朝阳区建国路88号',
        created_at: '2024-03-01 09:00:00',
        priority: 'high',
        status: 'pending'
      },
      {
        id: 2,
        order_number: 'ORD20240301002',
        customer_name: '公司B',
        address: '北京市海淀区中关村大街1号',
        created_at: '2024-03-01 10:30:00',
        priority: 'medium',
        status: 'pending'
      },
      {
        id: 3,
        order_number: 'ORD20240301003',
        customer_name: '公司C',
        address: '北京市西城区西单大悦城',
        created_at: '2024-03-01 11:15:00',
        priority: 'low',
        status: 'pending'
      }
    ]

    // 使用与配送员仪表盘相同的统计数据
    stats.value = {
      ...stats.value,
      pending_orders: 3,        // 待分配订单数
      delivering_orders: 5,     // 配送中订单数
      completed_orders: 8,      // 今日完成订单数
      total_orders: 16,         // 总订单数（3 + 5 + 8）
      total_deliveries: 3       // 配送员数量
    }

    // 生成趋势图数据
    // 使用最近7天的模拟数据
    orderTrendData.value.week = [4, 6, 3, 8, 5, 7, 6]
    // 使用最近30天的模拟数据
    orderTrendData.value.month = Array.from({length: 30}, () => 
      Math.floor(Math.random() * 10) + 3
    )

    // 添加最新订单到动态
    mockOrders.forEach(order => {
      let statusText = ''
      switch (order.status) {
        case 'pending':
          statusText = '待处理'
          break
        case 'delivering':
          statusText = '配送中'
          break
        case 'completed':
          statusText = '已完成'
          break
        default:
          statusText = order.status
      }
      
      recentActivities.value.push({
        type: 'primary',
        content: `新订单 #${order.id} (${statusText})`,
        time: new Date(order.created_at).toLocaleString()
      })
    })

    console.log('Mock orders loaded:', stats.value)
  } catch (error) {
    console.error('获取订单数据失败:', error)
    ElMessage.error('获取订单数据失败')
  }
}

// 获取配送数据
const fetchDeliveries = async () => {
  try {
    console.log('Fetching deliveries...')
    // 使用模拟数据，与配送员仪表盘保持一致
    const mockDeliveries = [
      {
        id: 1,
        delivery_number: 'DEL20240301001',
        order_id: 1,
        delivery_staff: '配送员A',
        status: 'pending',
        created_at: '2024-03-01 09:30:00'
      },
      {
        id: 2,
        delivery_number: 'DEL20240301002',
        order_id: 2,
        delivery_staff: '配送员B',
        status: 'delivering',
        created_at: '2024-03-01 10:00:00'
      },
      {
        id: 3,
        delivery_number: 'DEL20240301003',
        order_id: 3,
        delivery_staff: '配送员C',
        status: 'completed',
        created_at: '2024-03-01 11:30:00'
      }
    ]

    // 更新统计数据，与配送员仪表盘保持一致
    stats.value.total_deliveries = 3 // 配送员数量
    stats.value.pending_deliveries = mockDeliveries.filter(delivery => delivery.status === 'pending').length
    
    // 添加最新配送任务到动态
    mockDeliveries.forEach(delivery => {
      let statusText = delivery.status === 'completed' ? '已完成' : 
                      delivery.status === 'delivering' ? '配送中' : '待处理'
      recentActivities.value.push({
        type: 'info',
        content: `配送任务 #${delivery.id} ${statusText}`,
        time: new Date(delivery.created_at).toLocaleString()
      })
    })

    console.log('Mock deliveries loaded:', stats.value)
  } catch (error) {
    console.error('获取配送数据失败:', error)
  }
}

// 修改用户趋势图为订单趋势图
const orderTrendOption = computed(() => {
  const isWeek = userChartRange.value === 'week'
  const days = isWeek ? 7 : 30
  const dates = Array.from({length: days}, (_, i) => {
    const date = new Date()
    date.setDate(date.getDate() - (days - 1 - i))
    return isWeek ? 
      ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()] :
      `${date.getMonth() + 1}/${date.getDate()}`
  })

  return {
    title: {
      text: '订单趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const value = params[0].value
        return `${params[0].name}<br/>订单数量：${value}`
      }
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: isWeek ? 0 : 45
      }
    },
    yAxis: {
      type: 'value',
      name: '订单数量'
    },
    series: [{
      name: '订单数量',
      data: isWeek ? orderTrendData.value.week : orderTrendData.value.month,
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      itemStyle: {
        color: '#409EFF'
      },
      lineStyle: {
        width: 2
      }
    }]
  }
})

// 修改订单分布图表配置
const orderDistributionOption = computed(() => ({
  title: {
    text: '订单状态分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: ['待处理', '配送中', '已完成']
  },
  series: [{
    type: 'pie',
    radius: '50%',
    data: [
      { value: stats.value.pending_orders, name: '待处理' },
      { value: stats.value.delivering_orders, name: '配送中' },
      { value: stats.value.completed_orders, name: '已完成' }
    ],
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }]
}))

// 更新用户趋势数据
const updateUserTrendData = (dates) => {
  // 这里可以根据实际数据更新趋势图
  // 示例代码仅作演示
}

// 更新订单分布数据
const updateOrderDistributionData = (orders) => {
  // 实际数据处理逻辑
}

// 获取所有统计数据
const fetchAllStats = async () => {
  try {
    recentActivities.value = [] // 清空活动列表
    await Promise.all([
      fetchUsers(),
      fetchProducts(),
      fetchOrders(),
      fetchDeliveries()
    ])
    // 按时间排序活动
    recentActivities.value.sort((a, b) => new Date(b.time) - new Date(a.time))
    console.log('All stats fetched successfully')
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败，请刷新页面重试')
  }
}

onMounted(() => {
  fetchAllStats()
})
</script>

<style scoped>
.admin-dashboard {
  padding: 24px;
}
.dashboard-stats {
  margin-top: 24px;
}
.dashboard-charts {
  margin-top: 24px;
}
.stat-title {
  font-size: 16px;
  color: #888;
}
.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-top: 8px;
}
.stat-trend {
  margin-top: 8px;
  font-size: 14px;
  color: #909399;
}
.stat-trend .up {
  color: #67C23A;
}
.stat-trend .down {
  color: #F56C6C;
}
.chart-card {
  margin-bottom: 20px;
}
.chart {
  height: 300px;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.timeline-card {
  margin-top: 20px;
}
</style> 